//
//  ThemeTableViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "ThemeTableViewController.h"
#import "Theme_lunbotu.h"
#import "ThemeTableViewCell.h"
#import "ThemeCellModel.h"
#import "ThemeDetailTableViewController.h"
#import "SDCycleScrollView.h"


@interface ThemeTableViewController ()<MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;
@property (nonatomic, strong) NSMutableArray *LBTDataArray;
@property (nonatomic, strong) NSMutableArray *themeDataArray;
@property (nonatomic, strong) UIImageView *tempIMGView;
@property (nonatomic, strong) NSMutableArray *imageURLArray;
@property (nonatomic, strong) NSMutableArray *tempImageURLArray;
@property (nonatomic, strong) NSMutableArray *LBTIMGArray;
@property (nonatomic, strong) SDCycleScrollView *carouselFigureScrollView;
@property (nonatomic, strong) ThemeCellModel *cellModel;
@property (nonatomic, strong) ThemeCellModel *changeCellFrameModel;
@property (nonatomic, strong) AppDelegate *app;

@end

@implementation ThemeTableViewController

- (void)dealloc
{
      [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
      _app = [[AppDelegate alloc] init];
     [self setLBTIMGArray];
    [self addCarouselFigure];
     [self addIndicatorView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
   [self freshHeader];
    [self setNavigationBar];
    [self addInternetObserver];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self setThemeData];

}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self addCarouselFigure];
    [self setThemeData];
}



- (void)setNavigationBar
{
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"TestNaviBar1.jpg"] forBarMetrics:(UIBarMetricsDefault)];
    self.navigationItem.title = @"主题游";
}


#pragma mark - delegate -
- (void)freshHeader
{
    if ([_app internetReachableOrNot]) {
        self.tableView.header = [LYBAnimationHeader headerWithRefreshingTarget:self refreshingAction:@selector(setThemeData)];
        [self.tableView.header beginRefreshing];
    } else {
        [self alertController];
    }
   
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark - event response -


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ThemeDetailTableViewController *detailVC = [[ThemeDetailTableViewController alloc] init];
    
    ThemeCellModel *model = self.themeDataArray[indexPath.row];
    
    detailVC.cellDetailUrl = [NSString stringWithFormat:@"http://mobileapp.roadqu.com/api/mobile/qunawan/tour/seasonfunplacelist?issue=%@&eachpage=20&startpos=0&token=562e0bf29f08d&mtid=%@&a_t=1445861250272&sign=12df81c7699e48587b2a9c33f2693167324f3e46", model.issue, model.mtid];
    detailVC.titleStr = model.name;
    detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark - methods -
- (NSArray *)setLBTIMGArray
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ThemeHeadIMG" ofType:@"plist"];
    NSArray *plistArray = [NSArray arrayWithContentsOfFile:path];
    self.LBTIMGArray = [NSMutableArray array];
    for (NSDictionary *dic in plistArray) {
        NSString *IMGUrl = [dic valueForKey:@"img"];
        [self.LBTIMGArray addObject:IMGUrl];
    }
    return self.LBTIMGArray;
}

- (void)setThemeData
{
    if ([_app internetReachableOrNot]) {
        self.themeDataArray = [NSMutableArray array];

    NSString *themeUrlStr = @"http://mobileapp.roadqu.com/api/mobile/qunawan/tour/featuredthemeslist?token=562e0bf29f08d&a_t=1445859122827&sign=d61f73f3011a04853eb62c2a49d487a8a19eb598";
    NSMutableURLRequest *themeRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:themeUrlStr] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    
    NSURLSessionConfiguration *themeConfig = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *themeSession = [NSURLSession sessionWithConfiguration:themeConfig];
    
    NSURLSessionDataTask *themeDask = [themeSession dataTaskWithRequest:themeRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
             NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
            return ;
        }
        NSDictionary *themeDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSMutableArray *themeArray = [themeDic valueForKey:@"data"];
        for (NSDictionary *dic in themeArray) {
            ThemeCellModel *model = [[ThemeCellModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.themeDataArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.header endRefreshing];
            [self.tableView reloadData];
            [self.indicatorView stopAnimating];

        });
    }];
    
    [themeDask resume];
        
    } else {
        [self.indicatorView stopAnimating];
        [self alertController];
    }

}

#pragma mark - setters and getters -
/** 
 添加轮播图
 */


- (void)addCarouselFigure
{
   
    
    self.carouselFigureScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 210) imageURLStringsGroup:[self setLBTIMGArray]];
    // 几秒钟换图片
    self.carouselFigureScrollView.autoScrollTimeInterval = 2.5;
    // 小圆点的颜色
    self.carouselFigureScrollView.dotColor = [UIColor blueColor];
    // 小圆点的位置在中间还是右边
    self.carouselFigureScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    // 设置代理
//    self.carouselFigureScrollView.delegate = self;
    self.tableView.tableHeaderView = self.carouselFigureScrollView;
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.themeDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *themeIdentifier = @"themeIdentifier";
    ThemeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:themeIdentifier];
    if (cell == nil) {
        cell = [[ThemeTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:themeIdentifier];
    }
    if (self.themeDataArray.count > 0) {
        ThemeCellModel *model = self.themeDataArray[indexPath.row];
        
        if (indexPath.row == 4) {
            cell.themeNameTXT.frame = CGRectMake(kScreenWidth - 100, 160, 70, 20);
            cell.backView.frame = CGRectMake(kScreenWidth - 100, 160, 70, 20);
        } else if (indexPath.row == 0) {
            cell.themeNameTXT.frame = CGRectMake(kScreenWidth - 80, 160, 45, 20);
            cell.backView.frame = CGRectMake(kScreenWidth - 80, 160, 45, 20);
        }
            cell.themeTitleTXT.text = [NSString stringWithFormat:@"   %@",model.desc];
            cell.themeNameTXT.text = model.name;
            [cell.themeIMGView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
      }
    
    return cell;
}


#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.frame = CGRectMake((kScreenWidth - 100) / 2, (kScreenHeight - 50) / 2, 100, 50);
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 8; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}



@end
